package cn.edu.zsc.rbac.service.array;

import cn.edu.zsc.rbac.domain.dto.DeptDto;
import cn.edu.zsc.rbac.domain.entity.Dept;
import cn.edu.zsc.rbac.domain.vo.DeptVo;
import cn.edu.zsc.rbac.domain.vo.Result;
import cn.edu.zsc.rbac.service.IDeptService;
import cn.edu.zsc.rbac.service.IUserService;

import java.time.LocalDateTime;


/**
 * 业务层-部门
 *
 * @author 陈奕君
 * @since 2025/4/15 18:29
 */
public class DeptService extends BaseService<Dept, DeptDto , DeptVo> implements IDeptService {

    private IUserService userService;

    private static IDeptService singleton;

    private DeptService() {
        data = new Dept[DATA_SIZE + 1];
        temp = new DeptVo[DATA_SIZE];
    }

    public static IDeptService getInstance() {
       if(singleton == null) {
           singleton = new DeptService();
       }
           return singleton;
    }

    @Override
    DeptVo convertToVo(Dept dept) {
        return new DeptVo(dept.getId(), dept.createAt,  dept.updateAt, dept.name, dept.phone);
    }

    @Override
    Dept createEntity(DeptDto dto,int id)
    {
        LocalDateTime now = LocalDateTime.now();
        return new Dept(id,now,now,dto.name,dto.phone);
    }

    @Override
    void updateEntity(DeptDto dto,Dept dept)
    {
        dept.updateAt = LocalDateTime.now();
        dept.name = dto.name;
        dept.phone = dto.phone;
    }

    @Override
    public  Result delete(int id) {
        if (!existsById(id)) {
            return Result.failure("删除部门失败，部门不存在！");
        }
        if(userService == null){
            userService = UserService.getInstance();
        }
        if(userService.deptInUse(id)){
            return Result.failure("删除失败，还有用户属于该部门，不能删除！");
        }
        data[id] = null;
        return Result.success("删除部门成功！", id);
    }
}